import sys
import threading

from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox

from MainWindow import Ui_MainWindow
from bilibili_download import BilibiliDownload


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.download)
        self.bilibili_download = BilibiliDownload()
        self.menu_action.triggered.connect(self.on_click_help)
        self.msgBox.buttonClicked.connect(lambda x: self.lineEdit.setText(''))

    def on_click_help(self):
        self.help_info.exec()

    def download(self):
        share_link = self.lineEdit.text()
        if len(share_link) == 0:
            return
        self.bilibili_download.share_link = share_link
        print('download...')
        # threads = []
        task = threading.Thread(target=self.bilibili_download.download_share)
        task.start()
        task.join()
        print("下载完成")
        if not self.bilibili_download.filenames:
            download_text = '视频或者图文不存在'
        else:
            download_text = f'文件保存至{self.bilibili_download.filenames[0]}：\n'
            for i in range(1,len(self.bilibili_download.filenames)):
                download_text += f'{self.bilibili_download.filenames[i]}下载完成\n'
        self.msgBox.setText(download_text)
        self.msgBox.exec()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec())
